package mark.tom.pistols.algorithm.encryption;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public final class RSAEncryption {

    public static byte[] encrypt(String publicKey, byte[] data) throws Exception {
        // 使用默认RSA
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publicKey));
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(String privateKey, byte[] data) throws Exception {
        // 使用默认RSA
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, loadPrivateKey(privateKey));
        return cipher.doFinal(data);
    }

    private static RSAPublicKey loadPublicKey(String publicKey) throws Exception {
        byte[] buffer = Base64Encryption.decrypt(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

    private static RSAPrivateKey loadPrivateKey(String privateKey) throws Exception {
        byte[] buffer = Base64Encryption.decrypt(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }
}
